from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User,Addr
import re
import string
import random
from captcha.image import ImageCaptcha
from django.http import HttpResponse
import redis
from decorator.decorator import check_login
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import check_password
import jwt
import time
from django.conf import settings
from .serializer import UserSer,AddrSer
from rest_framework_jwt.utils import jwt_payload_handler,jwt_encode_handler
from django.db import models

# Create your views here.
# class Logout(APIView):
#     def get(self,request):
#         return Response({"code":200, "msg":"测试django跨域"})


# 校验用户名是否重复
class CheckUsername(APIView):
    def get(self,request,username):
        # 1.查询当前用户名是否存在
        try:
            user = User.objects.get(username=username)
        except:
            return Response({"code":200, "msg":"用户名可以使用"})

        return Response({"code":204, "msg":"用户名已注册"})

# 校验手机号的重复性
class CheckMobile(APIView):
    def get(self,request,mobile):

        # 1.验证手机号 是否满足规则
        # 手机号以1开头，第二位3-9之间的数字，长度为11，只允许数字
        if not re.findall(r"^1[3-9]\d{9}$",mobile):
            return Response({"code":204, "msg":"手机号不合法"})


        # 2.根据手机号 查询用户 ， 如果能查询到用户, 说明已经注册
        # 手机号 不能再注册
        user_query_set = User.objects.filter(mobile=mobile)

        if not user_query_set:
            return Response({"code":200, "msg":"可以正常注册"})
        return Response({"code":204, "msg":"手机号已注册"})

# 图片验证码
class GenImageCode(APIView):
    def get(self,request,uuid):
        print("uuid", uuid, type(uuid))

        # 1.生成随机字符串
        alpha_number = string.ascii_letters+string.digits
        img_code = "".join(random.sample(alpha_number,4))
        print("image_code:", img_code)

        # 2.生成图片验证码
        img_cap = ImageCaptcha()
        img_code_captcha = img_cap.generate(img_code)
        print("img_code:", img_code)

        # 3.存储图片验证码
        redis_conn = redis.Redis(host='localhost', port=6379, db=0, password='123')
        key = "image_code:%s"%uuid
        redis_conn.set(key, img_code, ex=300)

        redis_conn.close()

        return HttpResponse(img_code_captcha, content_type="image/png")

# 校验图片验证码
class CheckImageCode(APIView):
    def get(self,request):
        # 1.获取前端数据
        uuid_ = request.query_params.get("imageCodeID")
        image_code_ = request.query_params.get("imageCode")

        # 2.根据uuid 构造key
        key = "image_code:%s"%uuid_

        # 3.读取redis存储的验证码
        redis_conn = redis.Redis(host="localhost", port=6379, db=0, password='123')
        stored_image_code = redis_conn.get(key)

        if not stored_image_code:
            return Response({"code":204, "msg":"图片验证码已过期"})
        print("验证码：", stored_image_code)
        # 校验验证码是否全为小写
        if stored_image_code.decode().lower() == image_code_.lower():
            return Response({"code":200, "msg":"验证成功"})

        return Response({"code":204, "msg":"验证码输入错误"})

# 用户注册
class Register(APIView):
    def post(self,request):
        # 1.获取前端数据
        username = request.data.get("userName")
        password = request.data.get("pwd")
        mobile = request.data.get("mobile")
        aggrement = request.data.get("agree")
        print("agree:", aggrement)

        # 2.简单验证
        if not all([username,password,mobile,aggrement]):
            return Response({"code":204, "msg":"用户信息不完整"})


        # 3.创建用户对象,并存储
        User.objects.create_user(username=username,password=password,mobile=mobile)


        return Response({"code":200, "msg":"注册成功"})

# 用户登录
class Login(APIView):
    def post(self,request):

        # 1.获取前端数据
        username = request.data.get("user")
        password = request.data.get("pwd")

        # 2.查询用户
        try:
            user = User.objects.get(models.Q(username=username) | models.Q(mobile=username))
        except:
            return Response({"code":204, "msg":"用户不存在"})

        # 3.验证密码
        validate = check_password(password, user.password)
        if validate:
            # 验证通过,允许登录
            # request.session['username'] = username
            token = self.gen_token(user)
            return Response({"code":200, "msg":"欢迎%s"%username, 'user':{'userName':username},'token':token})

        return Response({"code":204, "msg":"用户名或者密码错误"})

    @staticmethod
    def gen_token(user):

        payload = {
            'username':user.username,
            'exp':time.time() + 300000
        }

        # 使用jwt编码，生成token
        token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
        # payload = jwt_payload_handler(user)
        # token = jwt_encode_handler(payload)

        return token

# 退出登录
class Logout(APIView):
    def get(self,request):

        if request.session.get("username"):
#             删除服务端的session信息
            del request.session['username']

        return Response({"code":200, "msg":"退出登录成功"})